package middleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/ifnk/micro-blog/internal/blog/global"
	response "github.com/ifnk/micro-blog/internal/pkg/http"
	"github.com/ifnk/micro-blog/internal/pkg/utils"
	"github.com/ifnk/micro-blog/protobuf/permission_pb"
)

// 拦截器
func CasbinHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		waitUse, _ := utils.GetClaims(c)
		// 获取请求的PATH
		obj := c.Request.URL.Path
		// 获取请求方法
		act := c.Request.Method
		// 获取用户的角色
		sub := waitUse.AuthorityIds
		// 判断策略中是否存在(远程grpc 调用 )
		claim, err := global.CasbinClient.CheckExistsByClaim(c, &permission_pb.CheckExistsByClaimRequest{AuthorityIds: sub, Method: act, Path: obj})
		if err != nil {
			response.FailWithDetailed(gin.H{}, fmt.Sprintf("查询权限出错 -> %+v", err), c)
			c.Abort()
			return
		}
		if claim.GetSuccess() {
			c.Next()
		} else {
			sprint := fmt.Sprintf("当前角色 权限不足 ->HTTP %+v  %+v", act, obj)
			response.FailWithDetailed(gin.H{}, sprint, c)
			c.Abort()
			return
		}

	}
}
